package com.gy.boot.common.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gy.boot.common.util.BlankUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/WebSocket/{id}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    // concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private static final String LOCK_ID = "WEB_SOCKET_"; // 同步锁

    /**
     * 连接数 + 1
     */
    private static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    /**
     * 连接数 - 1
     */
    private static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    /**
     * 发送消息
     */
    private void sendMessage(Session session, String message) throws IOException {
        if (session == null) {
            return;
        }
        System.out.println("session_id = " + session.getId());
        synchronized ((LOCK_ID + session.getId()).intern()) {
            System.out.println("发送数据：" + message);
            session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 给指定用户发送信息
     */
    public void sendMsg(String id, String msg) {
        Session session = sessionPools.get(id);
        try {
            sendMessage(session, msg);
        } catch (Exception e) {
            System.out.println("指定用户发送信息失败");
            log.error("消息发送失败: {id:" + id + ", msg:'" + msg + "'}", e);
        }
    }

    /**
     * 建立连接成功调用
     * */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id) {
        if (BlankUtil.isBlank(id)) {
            return;
        }
        Session session_old = sessionPools.get(id);
        if (session_old != null) {
            sendMsg(id, "您的账号在其他地方登录, 当前账号关闭消息通道");
        }
        sessionPools.put(id, session);
        addOnlineCount();
        System.out.println(id + "加入webSocket！当前人数为" + onlineNum);
        try {
            sendMessage(session, "欢迎" + id + "加入连接！");
        } catch (IOException e) {
            System.out.println("建立连接成功信息失败");
            log.error("消息发送失败: {id:" + id + ", msg: '建立连接成功'}", e);
        }
    }

    /**
     * 关闭连接时调用
     */
    @OnClose
    public void onClose(@PathParam(value = "id") String id) {
        if (BlankUtil.isBlank(id)) {
            return;
        }
        sessionPools.remove(id);
        subOnlineCount();
        System.out.println(id + "断开webSocket连接！当前人数为" + onlineNum);
    }

    /**
     * 单人-对-单人发送消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam(value = "id") String id) {
        if (BlankUtil.isBlank(id)) {
            return;
        }
        if (JSONUtil.isJson(message)) {
            JSONObject params = JSONUtil.parseObj(message);
            String toUserId = params.getStr("toUserId");
            String msg = params.getStr("msg");
            String msg2 = id + ": " + msg;
            sendMsg(toUserId, msg2); // 单人-对-单人发送消息
        }
    }

    /**
     * 发送广播
     * */
    public void sendRadio(String msg) {
        Set<Map.Entry<String, Session>> userSet = sessionPools.entrySet();
        for (Map.Entry<String, Session> user : userSet) {
            String id = user.getKey();
            System.out.println(id + " 广播: " + msg);
            sendMsg(id, msg); // 发送广播
        }
    }

    /**
     * 错误时调用
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        log.error("WebSocket连接异常, ", throwable);
    }

}
